/**
 * 熵巡 - 企业级氚云OpenAPI数据管理平台
 * 开发归属 Alyr.net
 * 云数据库模块
 * 尊重劳动成果是一种美德
 */

// 页面加载后初始化
document.addEventListener('DOMContentLoaded', function() {
    console.log('cloud-database.js 已加载');
});

// 初始化云数据库内部TAB - 全局函数
window.initCloudDatabaseTabs = function() {
    console.log('初始化云数据库内部TAB');
    const cloudDatabaseSection = document.getElementById('cloud-database');
    if (!cloudDatabaseSection) {
        console.log('未找到云数据库区域');
        return;
    }
    
    // 只处理云数据库内部的TAB链接
    const tabLinks = cloudDatabaseSection.querySelectorAll('.cloud-sub-tab');
    console.log('找到云数据库子TAB数量:', tabLinks.length);
    
    // 为内部TAB链接添加点击事件
    tabLinks.forEach(function(link) {
        // 先移除已有的事件监听器
        link.removeEventListener('click', handleCloudSubTabClick);
        // 添加新的事件监听器
        link.addEventListener('click', handleCloudSubTabClick);
    });
    
    // 默认激活第一个子TAB
    if (tabLinks.length > 0) {
        tabLinks[0].classList.add('active');
    }
};

// 处理云数据库子TAB点击
function handleCloudSubTabClick(e) {
    e.preventDefault();
    console.log('云数据库子TAB被点击');
    
    const cloudDatabaseSection = document.getElementById('cloud-database');
    const tabLinks = cloudDatabaseSection.querySelectorAll('.cloud-sub-tab');
    
    // 移除所有云数据库内部TAB的活动状态
    tabLinks.forEach(function(l) {
        l.classList.remove('active');
    });
    
    // 添加当前活动状态
    this.classList.add('active');
    const targetId = this.getAttribute('data-tab');
    
    // 加载对应内容
    if (targetId === 'tencent-cloud') {
        window.loadTencentCloudContent();
    }
}

// 加载腾讯云数据库内容 - 全局函数
window.loadTencentCloudContent = function() {
    console.log('开始加载腾讯云数据库内容');
    const tencentCloudSection = document.getElementById('tencent-cloud');
    if (!tencentCloudSection) {
        console.log('未找到腾讯云区域元素');
        return;
    }
    
    const html = `
        <div class="query-panel">
            <div class="query-filters">
                <h4>腾讯云数据库配置</h4>
                <div class="filter-container">
                    <label>连接地址:</label>
                    <input type="text" id="tencent-host" placeholder="数据库连接地址">
                    
                    <label>端口:</label>
                    <input type="text" id="tencent-port" placeholder="3306" value="3306">
                    
                    <label>数据库名:</label>
                    <input type="text" id="tencent-database" placeholder="数据库名称">
                    
                    <label>用户名:</label>
                    <input type="text" id="tencent-username" placeholder="数据库用户名">
                    
                    <label>密码:</label>
                    <input type="password" id="tencent-password" placeholder="数据库密码">
                    
                    <button class="btn btn-primary" onclick="testTencentConnection()">测试连接</button>
                    <button class="btn btn-secondary" onclick="saveTencentConfig()">保存配置</button>
                </div>
            </div>
            
            <div class="query-header">
                <span id="tencent-status" class="query-status">请配置腾讯云数据库连接信息</span>
            </div>
            
            <div id="tencent-results" class="query-results">
                <!-- 连接结果将显示在这里 -->
            </div>
        </div>
    `;
    
    tencentCloudSection.innerHTML = html;
    console.log('腾讯云数据库内容已插入到DOM中');
}

// 测试腾讯云连接
function testTencentConnection() {
    const statusElement = document.getElementById('tencent-status');
    const resultsElement = document.getElementById('tencent-results');
    
    statusElement.textContent = '正在测试连接...';
    statusElement.className = 'query-status';
    
    // 获取配置信息
    const config = {
        host: document.getElementById('tencent-host').value,
        port: document.getElementById('tencent-port').value,
        database: document.getElementById('tencent-database').value,
        username: document.getElementById('tencent-username').value,
        password: document.getElementById('tencent-password').value
    };
    
    // 验证必填字段
    if (!config.host || !config.database || !config.username || !config.password) {
        statusElement.textContent = '请填写完整的连接信息';
        return;
    }
    
    // 这里可以添加实际的连接测试逻辑
    setTimeout(() => {
        statusElement.textContent = '连接测试功能开发中...';
        resultsElement.innerHTML = '<p>腾讯云数据库连接功能正在开发中，敬请期待。</p>';
    }, 1000);
}

// 保存腾讯云配置
function saveTencentConfig() {
    const config = {
        host: document.getElementById('tencent-host').value,
        port: document.getElementById('tencent-port').value,
        database: document.getElementById('tencent-database').value,
        username: document.getElementById('tencent-username').value,
        password: document.getElementById('tencent-password').value
    };
    
    // 验证必填字段
    if (!config.host || !config.database || !config.username || !config.password) {
        alert('请填写完整的连接信息');
        return;
    }
    
    // 这里可以添加实际的配置保存逻辑
    alert('配置保存功能开发中...');
}

// MySQL服务开关切换 - 全局函数
window.toggleMysqlService = async function() {
    const enabledCheckbox = document.getElementById('mysql-enabled');
    const statusText = document.getElementById('mysql-status-text');
    const configForm = document.getElementById('mysql-config-form');
    
    const isEnabled = enabledCheckbox.checked;
    
    // 如果要启用MySQL，需要先检查并禁用其他数据库
    if (isEnabled) {
        const result = await window.checkAndDisableOtherDatabases('mysql');
        if (!result) {
            // 如果用户取消操作，恢复开关状态
            enabledCheckbox.checked = false;
            return;
        }
    }
    
    // 自动保存配置
    const config = {
        type: 'mysql',
        enabled: isEnabled,
        secret_id: document.getElementById('mysql-secret-id').value,
        secret_key: document.getElementById('mysql-secret-key').value,
        region: document.getElementById('mysql-region').value,
        instance_id: document.getElementById('mysql-instance-id').value,
        host: document.getElementById('mysql-host').value,
        port: document.getElementById('mysql-port').value,
        database: document.getElementById('mysql-database').value,
        username: document.getElementById('mysql-username').value,
        password: document.getElementById('mysql-password').value
    };
    
    try {
        const response = await fetch('api/save_database_config.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: new URLSearchParams(config)
        });
        
        const text = await response.text();
        const data = JSON.parse(text);
        
        if (data.success) {
            // 更新状态文本
            statusText.textContent = isEnabled ? '已启用' : '已禁用';
            
            // 更新表单可用性
            const formInputs = configForm.querySelectorAll('input, select, button');
            formInputs.forEach(input => {
                input.disabled = !isEnabled;
            });
            
            // 更新表单样式
            if (isEnabled) {
                configForm.style.opacity = '1';
                configForm.style.pointerEvents = 'auto';
            } else {
                configForm.style.opacity = '0.6';
                configForm.style.pointerEvents = 'none';
            }
            
            console.log('MySQL服务状态已自动保存:', isEnabled ? '启用' : '禁用');
        } else {
            alert('保存失败：' + data.message);
            // 恢复开关状态
            enabledCheckbox.checked = !isEnabled;
        }
    } catch (error) {
        alert('保存失败：' + error.message);
        // 恢复开关状态
        enabledCheckbox.checked = !isEnabled;
    }
};

// 检查并禁用其他数据库服务 - 全局函数
window.checkAndDisableOtherDatabases = async function(currentDb) {
    const dbNames = {
        'mysql': 'MySQL',
        'tdsql_c': 'TDSQL-C', 
        'sql_server': 'SQL Server',
        'postgresql': 'PostgreSQL'
    };
    
    try {
        // 获取当前所有数据库的状态
        const response = await fetch('api/get_database_states.php');
        const data = await response.json();
        
        if (data.success) {
            const otherEnabledDbs = [];
            
            // 检查其他数据库是否有启用的
            Object.keys(data.database_states).forEach(db => {
                if (db !== currentDb && data.database_states[db]) {
                    otherEnabledDbs.push(dbNames[db]);
                }
            });
            
            if (otherEnabledDbs.length > 0) {
                // 如果有其他启用的数据库，显示确认对话框
                const currentDbName = dbNames[currentDb];
                const otherDbList = otherEnabledDbs.join('、');
                const message = `启用 ${currentDbName} 将自动禁用以下数据库服务：

${otherDbList}

系统同时只能启用一个云数据库服务。

确定要继续吗？`;
                
                const confirmed = confirm(message);
                if (confirmed) {
                    console.log(`用户确认启用 ${currentDbName}，将禁用: ${otherDbList}`);
                    return true;
                } else {
                    console.log(`用户取消启用 ${currentDbName}`);
                    return false;
                }
            } else {
                // 没有其他启用的数据库，直接允许
                console.log(`没有其他启用的数据库，允许启用 ${dbNames[currentDb]}`);
                return true;
            }
        } else {
            console.error('获取数据库状态失败:', data.message);
            // 如果获取状态失败，显示简化的确认对话框
            const currentDbName = dbNames[currentDb];
            const message = `启用 ${currentDbName} 将自动禁用其他所有云数据库服务。

系统同时只能启用一个云数据库服务。

确定要继续吗？`;
            return confirm(message);
        }
    } catch (error) {
        console.error('检查数据库状态出错:', error);
        // 如果请求失败，显示简化的确认对话框
        const currentDbName = dbNames[currentDb];
        const message = `启用 ${currentDbName} 将自动禁用其他所有云数据库服务。

系统同时只能启用一个云数据库服务。

确定要继续吗？`;
        return confirm(message);
    }
};

// MySQL数据库测试连接 - 全局函数
window.testMysqlConnection = function() {
    const config = {
        type: 'mysql',
        secret_id: document.getElementById('mysql-secret-id').value,
        secret_key: document.getElementById('mysql-secret-key').value,
        region: document.getElementById('mysql-region').value,
        instance_id: document.getElementById('mysql-instance-id').value,
        host: document.getElementById('mysql-host').value,
        port: document.getElementById('mysql-port').value,
        database: document.getElementById('mysql-database').value,
        username: document.getElementById('mysql-username').value,
        password: document.getElementById('mysql-password').value
    };
    
    if (!config.secret_id || !config.secret_key || !config.region || !config.host || !config.database || !config.username) {
        alert('请填写完整的连接信息和腾讯云API配置');
        return;
    }
    
    const testBtn = event.target;
    const originalText = testBtn.textContent;
    testBtn.textContent = '测试中...';
    testBtn.disabled = true;
    
    fetch('api/test_database_connection.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: new URLSearchParams(config)
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('HTTP 错误: ' + response.status);
        }
        return response.text();
    })
    .then(text => {
        try {
            const data = JSON.parse(text);
            if (data.success) {
                alert('连接成功！');
            } else {
                alert('连接失败：' + data.message);
            }
        } catch (e) {
            console.error('返回内容:', text);
            alert('返回数据解析错误: ' + e.message);
        }
    })
    .catch(error => {
        alert('测试失败：' + error.message);
    })
    .finally(() => {
        testBtn.textContent = originalText;
        testBtn.disabled = false;
    });
};

// MySQL数据库保存配置 - 全局函数
window.saveMysqlConfig = function() {
    const config = {
        type: 'mysql',
        enabled: document.getElementById('mysql-enabled').checked,
        secret_id: document.getElementById('mysql-secret-id').value,
        secret_key: document.getElementById('mysql-secret-key').value,
        region: document.getElementById('mysql-region').value,
        instance_id: document.getElementById('mysql-instance-id').value,
        host: document.getElementById('mysql-host').value,
        port: document.getElementById('mysql-port').value,
        database: document.getElementById('mysql-database').value,
        username: document.getElementById('mysql-username').value,
        password: document.getElementById('mysql-password').value
    };
    
    if (!config.secret_id || !config.secret_key || !config.region) {
        alert('请填写完整的腾讯云API配置信息');
        return;
    }
    
    const saveBtn = event.target;
    const originalText = saveBtn.textContent;
    saveBtn.textContent = '保存中...';
    saveBtn.disabled = true;
    
    // 使用新的通用API接口
    fetch('api/save_database_config.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: new URLSearchParams(config)
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('HTTP 错误: ' + response.status);
        }
        return response.text();
    })
    .then(text => {
        try {
            const data = JSON.parse(text);
            if (data.success) {
                alert('配置保存成功！');
                
                // 如果返回了数据库状态信息，显示互斥结果
                if (data.database_states) {
                    const enabledDb = Object.keys(data.database_states).find(db => data.database_states[db]);
                    if (enabledDb && enabledDb !== 'mysql') {
                        console.log('其他数据库已被禁用，当前启用:', enabledDb);
                    } else if (enabledDb === 'mysql') {
                        console.log('MySQL已启用，其他数据库已禁用');
                    }
                }
            } else {
                alert('配置保存失败：' + data.message);
            }
        } catch (e) {
            console.error('返回内容:', text);
            alert('返回数据解析错误: ' + e.message);
        }
    })
    .catch(error => {
        alert('保存失败：' + error.message);
    })
    .finally(() => {
        saveBtn.textContent = originalText;
        saveBtn.disabled = false;
    });
};

// MySQL上传SQL文件 - 全局函数
window.uploadMysqlSql = function() {
    const fileInput = document.getElementById('mysql-sql-file');
    fileInput.click();
};

// 处理MySQL SQL文件上传 - 全局函数  
window.handleMysqlSqlFile = function(input) {
    const file = input.files[0];
    if (!file) {
        return;
    }
    
    if (!file.name.endsWith('.sql')) {
        alert('请上传.sql文件');
        input.value = '';
        return;
    }
    
    if (!confirm(`确认要执行 SQL 文件 "${file.name}" 吗？\n\n请确保数据库配置正确，并已备份重要数据！`)) {
        input.value = '';
        return;
    }
    
    const formData = new FormData();
    formData.append('sql_file', file);
    formData.append('db_type', 'mysql');
    
    const uploadBtn = document.querySelector('.btn-success');
    const originalText = uploadBtn.textContent;
    uploadBtn.textContent = '上传执行中...';
    uploadBtn.disabled = true;
    
    fetch('database/mysql/execute-sql.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert(`SQL执行成功！\n\n${data.message || ''}`);
        } else {
            alert(`SQL执行失败：${data.message}`);
        }
    })
    .catch(error => {
        alert('上传失败：' + error.message);
    })
    .finally(() => {
        uploadBtn.textContent = originalText;
        uploadBtn.disabled = false;
        input.value = ''; // 清空文件输入
    });
};

// TDSQL-C上传SQL文件 - 全局函数
window.uploadTdsqlSql = function() {
    const fileInput = document.getElementById('tdsql-sql-file');
    fileInput.click();
};

// 处理TDSQL-C SQL文件上传 - 全局函数
window.handleTdsqlSqlFile = function(input) {
    const file = input.files[0];
    if (!file) {
        return;
    }
    
    if (!file.name.endsWith('.sql')) {
        alert('请上传.sql文件');
        input.value = '';
        return;
    }
    
    if (!confirm(`确认要执行 SQL 文件 "${file.name}" 吗？\n\n请确保数据库配置正确，并已备份重要数据！`)) {
        input.value = '';
        return;
    }
    
    const formData = new FormData();
    formData.append('sql_file', file);
    formData.append('db_type', 'tdsql_c');
    
    const uploadBtn = document.querySelector('#tdsql-config-form .btn-success');
    const originalText = uploadBtn.textContent;
    uploadBtn.textContent = '上传执行中...';
    uploadBtn.disabled = true;
    
    fetch('database/tdsql-c/execute-sql.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert(`SQL执行成功！\n\n${data.message || ''}`);
        } else {
            alert(`SQL执行失败：${data.message}`);
        }
    })
    .catch(error => {
        alert('上传失败：' + error.message);
    })
    .finally(() => {
        uploadBtn.textContent = originalText;
        uploadBtn.disabled = false;
        input.value = ''; // 清空文件输入
    });
};

// SQL Server上传SQL文件 - 全局函数
window.uploadSqlServerSql = function() {
    const fileInput = document.getElementById('sqlserver-sql-file');
    fileInput.click();
};

// 处理SQL Server SQL文件上传 - 全局函数
window.handleSqlServerSqlFile = function(input) {
    const file = input.files[0];
    if (!file) {
        return;
    }
    
    if (!file.name.endsWith('.sql')) {
        alert('请上传.sql文件');
        input.value = '';
        return;
    }
    
    if (!confirm(`确认要执行 SQL 文件 "${file.name}" 吗？\n\n请确保数据库配置正确，并已备份重要数据！`)) {
        input.value = '';
        return;
    }
    
    const formData = new FormData();
    formData.append('sql_file', file);
    formData.append('db_type', 'sql_server');
    
    const uploadBtn = document.querySelector('#sqlserver-config-form .btn-success');
    const originalText = uploadBtn.textContent;
    uploadBtn.textContent = '上传执行中...';
    uploadBtn.disabled = true;
    
    fetch('database/sql-server/execute-sql.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert(`SQL执行成功！\n\n${data.message || ''}`);
        } else {
            alert(`SQL执行失败：${data.message}`);
        }
    })
    .catch(error => {
        alert('上传失败：' + error.message);
    })
    .finally(() => {
        uploadBtn.textContent = originalText;
        uploadBtn.disabled = false;
        input.value = ''; // 清空文件输入
    });
};

// PostgreSQL上传SQL文件 - 全局函数
window.uploadPostgreSqlSql = function() {
    const fileInput = document.getElementById('postgresql-sql-file');
    fileInput.click();
};

// 处理PostgreSQL SQL文件上传 - 全局函数
window.handlePostgreSqlSqlFile = function(input) {
    const file = input.files[0];
    if (!file) {
        return;
    }
    
    if (!file.name.endsWith('.sql')) {
        alert('请上传.sql文件');
        input.value = '';
        return;
    }
    
    if (!confirm(`确认要执行 SQL 文件 "${file.name}" 吗？\n\n请确保数据库配置正确，并已备份重要数据！`)) {
        input.value = '';
        return;
    }
    
    const formData = new FormData();
    formData.append('sql_file', file);
    formData.append('db_type', 'postgresql');
    
    const uploadBtn = document.querySelector('#postgresql-config-form .btn-success');
    const originalText = uploadBtn.textContent;
    uploadBtn.textContent = '上传执行中...';
    uploadBtn.disabled = true;
    
    fetch('database/postgresql/execute-sql.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert(`SQL执行成功！\n\n${data.message || ''}`);
        } else {
            alert(`SQL执行失败：${data.message}`);
        }
    })
    .catch(error => {
        alert('上传失败：' + error.message);
    })
    .finally(() => {
        uploadBtn.textContent = originalText;
        uploadBtn.disabled = false;
        input.value = ''; // 清空文件输入
    });
};

// SQL Server服务开关切换 - 全局函数
window.toggleSqlServerService = async function() {
    const enabledCheckbox = document.getElementById('sqlserver-enabled');
    const statusText = document.getElementById('sqlserver-status-text');
    const configForm = document.getElementById('sqlserver-config-form');
    
    const isEnabled = enabledCheckbox.checked;
    
    // 如果要启用SQL Server，需要先检查并禁用其他数据库
    if (isEnabled) {
        const result = await window.checkAndDisableOtherDatabases('sql_server');
        if (!result) {
            // 如果用户取消操作，恢复开关状态
            enabledCheckbox.checked = false;
            return;
        }
    }
    
    // 自动保存配置
    const config = {
        type: 'sql_server',
        enabled: isEnabled,
        secret_id: document.getElementById('sqlserver-secret-id').value,
        secret_key: document.getElementById('sqlserver-secret-key').value,
        region: document.getElementById('sqlserver-region').value,
        instance_id: document.getElementById('sqlserver-instance-id').value,
        host: document.getElementById('sqlserver-host').value,
        port: document.getElementById('sqlserver-port').value,
        database: document.getElementById('sqlserver-database').value,
        username: document.getElementById('sqlserver-username').value,
        password: document.getElementById('sqlserver-password').value
    };
    
    try {
        const response = await fetch('api/save_database_config.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: new URLSearchParams(config)
        });
        
        const text = await response.text();
        const data = JSON.parse(text);
        
        if (data.success) {
            // 更新状态文本
            statusText.textContent = isEnabled ? '已启用' : '已禁用';
            
            // 更新表单可用性
            const formInputs = configForm.querySelectorAll('input, select, button');
            formInputs.forEach(input => {
                input.disabled = !isEnabled;
            });
            
            // 更新表单样式
            if (isEnabled) {
                configForm.style.opacity = '1';
                configForm.style.pointerEvents = 'auto';
            } else {
                configForm.style.opacity = '0.6';
                configForm.style.pointerEvents = 'none';
            }
            
            console.log('SQL Server服务状态已自动保存:', isEnabled ? '启用' : '禁用');
        } else {
            alert('保存失败：' + data.message);
            // 恢复开关状态
            enabledCheckbox.checked = !isEnabled;
        }
    } catch (error) {
        alert('保存失败：' + error.message);
        // 恢复开关状态
        enabledCheckbox.checked = !isEnabled;
    }
};

// SQL Server数据库测试连接 - 全局函数
window.testSqlServerConnection = function() {
    const config = {
        type: 'sql_server',
        secret_id: document.getElementById('sqlserver-secret-id').value,
        secret_key: document.getElementById('sqlserver-secret-key').value,
        region: document.getElementById('sqlserver-region').value,
        instance_id: document.getElementById('sqlserver-instance-id').value,
        host: document.getElementById('sqlserver-host').value,
        port: document.getElementById('sqlserver-port').value,
        database: document.getElementById('sqlserver-database').value,
        username: document.getElementById('sqlserver-username').value,
        password: document.getElementById('sqlserver-password').value
    };
    
    if (!config.secret_id || !config.secret_key || !config.region || !config.host || !config.database || !config.username) {
        alert('请填写完整的连接信息和腾讯云API配置');
        return;
    }
    
    const testBtn = event.target;
    const originalText = testBtn.textContent;
    testBtn.textContent = '测试中...';
    testBtn.disabled = true;
    
    fetch('api/test_database_connection.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: new URLSearchParams(config)
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('HTTP 错误: ' + response.status);
        }
        return response.text();
    })
    .then(text => {
        try {
            const data = JSON.parse(text);
            if (data.success) {
                alert('连接成功！');
            } else {
                alert('连接失败：' + data.message);
            }
        } catch (e) {
            console.error('返回内容:', text);
            alert('返回数据解析错误: ' + e.message);
        }
    })
    .catch(error => {
        alert('测试失败：' + error.message);
    })
    .finally(() => {
        testBtn.textContent = originalText;
        testBtn.disabled = false;
    });
};

// SQL Server数据库保存配置 - 全局函数
window.saveSqlServerConfig = function() {
    const config = {
        type: 'sql_server',
        enabled: document.getElementById('sqlserver-enabled').checked,
        secret_id: document.getElementById('sqlserver-secret-id').value,
        secret_key: document.getElementById('sqlserver-secret-key').value,
        region: document.getElementById('sqlserver-region').value,
        instance_id: document.getElementById('sqlserver-instance-id').value,
        host: document.getElementById('sqlserver-host').value,
        port: document.getElementById('sqlserver-port').value,
        database: document.getElementById('sqlserver-database').value,
        username: document.getElementById('sqlserver-username').value,
        password: document.getElementById('sqlserver-password').value
    };
    
    if (!config.secret_id || !config.secret_key || !config.region) {
        alert('请填写完整的腾讯云API配置信息');
        return;
    }
    
    const saveBtn = event.target;
    const originalText = saveBtn.textContent;
    saveBtn.textContent = '保存中...';
    saveBtn.disabled = true;
    
    // 使用通用API接口
    fetch('api/save_database_config.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: new URLSearchParams(config)
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('HTTP 错误: ' + response.status);
        }
        return response.text();
    })
    .then(text => {
        try {
            const data = JSON.parse(text);
            if (data.success) {
                alert('配置保存成功！');
                
                // 如果返回了数据库状态信息，显示互斥结果
                if (data.database_states) {
                    const enabledDb = Object.keys(data.database_states).find(db => data.database_states[db]);
                    if (enabledDb === 'sql_server') {
                        console.log('SQL Server已启用，其他数据库已禁用');
                    }
                }
            } else {
                alert('配置保存失败：' + data.message);
            }
        } catch (e) {
            console.error('返回内容:', text);
            alert('返回数据解析错误: ' + e.message);
        }
    })
    .catch(error => {
        alert('保存失败：' + error.message);
    })
    .finally(() => {
        saveBtn.textContent = originalText;
        saveBtn.disabled = false;
    });
};

// PostgreSQL服务开关切换 - 全局函数
window.togglePostgreSqlService = async function() {
    const enabledCheckbox = document.getElementById('postgresql-enabled');
    const statusText = document.getElementById('postgresql-status-text');
    const configForm = document.getElementById('postgresql-config-form');
    
    const isEnabled = enabledCheckbox.checked;
    
    // 如果要启用PostgreSQL，需要先检查并禁用其他数据库
    if (isEnabled) {
        const result = await window.checkAndDisableOtherDatabases('postgresql');
        if (!result) {
            // 如果用户取消操作，恢复开关状态
            enabledCheckbox.checked = false;
            return;
        }
    }
    
    // 自动保存配置
    const config = {
        type: 'postgresql',
        enabled: isEnabled,
        secret_id: document.getElementById('postgresql-secret-id').value,
        secret_key: document.getElementById('postgresql-secret-key').value,
        region: document.getElementById('postgresql-region').value,
        instance_id: document.getElementById('postgresql-instance-id').value,
        host: document.getElementById('postgresql-host').value,
        port: document.getElementById('postgresql-port').value,
        database: document.getElementById('postgresql-database').value,
        username: document.getElementById('postgresql-username').value,
        password: document.getElementById('postgresql-password').value
    };
    
    try {
        const response = await fetch('api/save_database_config.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: new URLSearchParams(config)
        });
        
        const text = await response.text();
        const data = JSON.parse(text);
        
        if (data.success) {
            // 更新状态文本
            statusText.textContent = isEnabled ? '已启用' : '已禁用';
            
            // 更新表单可用性
            const formInputs = configForm.querySelectorAll('input, select, button');
            formInputs.forEach(input => {
                input.disabled = !isEnabled;
            });
            
            // 更新表单样式
            if (isEnabled) {
                configForm.style.opacity = '1';
                configForm.style.pointerEvents = 'auto';
            } else {
                configForm.style.opacity = '0.6';
                configForm.style.pointerEvents = 'none';
            }
            
            console.log('PostgreSQL服务状态已自动保存:', isEnabled ? '启用' : '禁用');
        } else {
            alert('保存失败：' + data.message);
            // 恢复开关状态
            enabledCheckbox.checked = !isEnabled;
        }
    } catch (error) {
        alert('保存失败：' + error.message);
        // 恢复开关状态
        enabledCheckbox.checked = !isEnabled;
    }
};

// PostgreSQL数据库测试连接 - 全局函数
window.testPostgreSqlConnection = function() {
    const config = {
        type: 'postgresql',
        secret_id: document.getElementById('postgresql-secret-id').value,
        secret_key: document.getElementById('postgresql-secret-key').value,
        region: document.getElementById('postgresql-region').value,
        instance_id: document.getElementById('postgresql-instance-id').value,
        host: document.getElementById('postgresql-host').value,
        port: document.getElementById('postgresql-port').value,
        database: document.getElementById('postgresql-database').value,
        username: document.getElementById('postgresql-username').value,
        password: document.getElementById('postgresql-password').value
    };
    
    if (!config.secret_id || !config.secret_key || !config.region || !config.host || !config.database || !config.username) {
        alert('请填写完整的连接信息和腾讯云API配置');
        return;
    }
    
    const testBtn = event.target;
    const originalText = testBtn.textContent;
    testBtn.textContent = '测试中...';
    testBtn.disabled = true;
    
    fetch('api/test_database_connection.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: new URLSearchParams(config)
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('HTTP 错误: ' + response.status);
        }
        return response.text();
    })
    .then(text => {
        try {
            const data = JSON.parse(text);
            if (data.success) {
                alert('连接成功！');
            } else {
                alert('连接失败：' + data.message);
            }
        } catch (e) {
            console.error('返回内容:', text);
            alert('返回数据解析错误: ' + e.message);
        }
    })
    .catch(error => {
        alert('测试失败：' + error.message);
    })
    .finally(() => {
        testBtn.textContent = originalText;
        testBtn.disabled = false;
    });
};

// PostgreSQL数据库保存配置 - 全局函数
window.savePostgreSqlConfig = function() {
    const config = {
        type: 'postgresql',
        enabled: document.getElementById('postgresql-enabled').checked,
        secret_id: document.getElementById('postgresql-secret-id').value,
        secret_key: document.getElementById('postgresql-secret-key').value,
        region: document.getElementById('postgresql-region').value,
        instance_id: document.getElementById('postgresql-instance-id').value,
        host: document.getElementById('postgresql-host').value,
        port: document.getElementById('postgresql-port').value,
        database: document.getElementById('postgresql-database').value,
        username: document.getElementById('postgresql-username').value,
        password: document.getElementById('postgresql-password').value
    };
    
    if (!config.secret_id || !config.secret_key || !config.region) {
        alert('请填写完整的腾讯云API配置信息');
        return;
    }
    
    const saveBtn = event.target;
    const originalText = saveBtn.textContent;
    saveBtn.textContent = '保存中...';
    saveBtn.disabled = true;
    
    // 使用通用API接口
    fetch('api/save_database_config.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: new URLSearchParams(config)
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('HTTP 错误: ' + response.status);
        }
        return response.text();
    })
    .then(text => {
        try {
            const data = JSON.parse(text);
            if (data.success) {
                alert('配置保存成功！');
                
                // 如果返回了数据库状态信息，显示互斥结果
                if (data.database_states) {
                    const enabledDb = Object.keys(data.database_states).find(db => data.database_states[db]);
                    if (enabledDb === 'postgresql') {
                        console.log('PostgreSQL已启用，其他数据库已禁用');
                    }
                }
            } else {
                alert('配置保存失败：' + data.message);
            }
        } catch (e) {
            console.error('返回内容:', text);
            alert('返回数据解析错误: ' + e.message);
        }
    })
    .catch(error => {
        alert('保存失败：' + error.message);
    })
    .finally(() => {
        saveBtn.textContent = originalText;
        saveBtn.disabled = false;
    });
};

// TDSQL-C服务开关切换 - 全局函数
window.toggleTdsqlService = async function() {
    const enabledCheckbox = document.getElementById('tdsql-enabled');
    const statusText = document.getElementById('tdsql-status-text');
    const configForm = document.getElementById('tdsql-config-form');
    
    const isEnabled = enabledCheckbox.checked;
    
    // 如枟要启用TDSQL-C，需要先检查并禁用其他数据库
    if (isEnabled) {
        const result = await window.checkAndDisableOtherDatabases('tdsql_c');
        if (!result) {
            // 如果用户取消操作，恢复开关状态
            enabledCheckbox.checked = false;
            return;
        }
    }
    
    // 自动保存配置
    const config = {
        type: 'tdsql_c',
        enabled: isEnabled,
        secret_id: document.getElementById('tdsql-secret-id').value,
        secret_key: document.getElementById('tdsql-secret-key').value,
        region: document.getElementById('tdsql-region').value,
        instance_id: document.getElementById('tdsql-instance-id').value,
        host: document.getElementById('tdsql-host').value,
        port: document.getElementById('tdsql-port').value,
        database: document.getElementById('tdsql-database').value,
        username: document.getElementById('tdsql-username').value,
        password: document.getElementById('tdsql-password').value
    };
    
    try {
        const response = await fetch('api/save_database_config.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: new URLSearchParams(config)
        });
        
        const text = await response.text();
        const data = JSON.parse(text);
        
        if (data.success) {
            // 更新状态文本
            statusText.textContent = isEnabled ? '已启用' : '已禁用';
            
            // 更新表单可用性
            const formInputs = configForm.querySelectorAll('input, select, button');
            formInputs.forEach(input => {
                input.disabled = !isEnabled;
            });
            
            // 更新表单样式
            if (isEnabled) {
                configForm.style.opacity = '1';
                configForm.style.pointerEvents = 'auto';
            } else {
                configForm.style.opacity = '0.6';
                configForm.style.pointerEvents = 'none';
            }
            
            console.log('TDSQL-C服务状态已自动保存:', isEnabled ? '启用' : '禁用');
        } else {
            alert('保存失败：' + data.message);
            // 恢复开关状态
            enabledCheckbox.checked = !isEnabled;
        }
    } catch (error) {
        alert('保存失败：' + error.message);
        // 恢复开关状态
        enabledCheckbox.checked = !isEnabled;
    }
};

// TDSQL-C数据库测试连接 - 全局函数
window.testTdsqlConnection = function() {
    const config = {
        type: 'tdsql_c',
        secret_id: document.getElementById('tdsql-secret-id').value,
        secret_key: document.getElementById('tdsql-secret-key').value,
        region: document.getElementById('tdsql-region').value,
        instance_id: document.getElementById('tdsql-instance-id').value,
        host: document.getElementById('tdsql-host').value,
        port: document.getElementById('tdsql-port').value,
        database: document.getElementById('tdsql-database').value,
        username: document.getElementById('tdsql-username').value,
        password: document.getElementById('tdsql-password').value
    };
    
    if (!config.secret_id || !config.secret_key || !config.region || !config.host || !config.database || !config.username) {
        alert('请填写完整的连接信息和腾讯云API配置');
        return;
    }
    
    const testBtn = event.target;
    const originalText = testBtn.textContent;
    testBtn.textContent = '测试中...';
    testBtn.disabled = true;
    
    fetch('api/test_database_connection.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: new URLSearchParams(config)
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('HTTP 错误: ' + response.status);
        }
        return response.text();
    })
    .then(text => {
        try {
            const data = JSON.parse(text);
            if (data.success) {
                alert('连接成功！');
            } else {
                alert('连接失败：' + data.message);
            }
        } catch (e) {
            console.error('返回内容:', text);
            alert('返回数据解析错误: ' + e.message);
        }
    })
    .catch(error => {
        alert('测试失败：' + error.message);
    })
    .finally(() => {
        testBtn.textContent = originalText;
        testBtn.disabled = false;
    });
};

// TDSQL-C数据库保存配置 - 全局函数
window.saveTdsqlConfig = function() {
    const config = {
        type: 'tdsql_c',
        enabled: document.getElementById('tdsql-enabled').checked,
        secret_id: document.getElementById('tdsql-secret-id').value,
        secret_key: document.getElementById('tdsql-secret-key').value,
        region: document.getElementById('tdsql-region').value,
        instance_id: document.getElementById('tdsql-instance-id').value,
        host: document.getElementById('tdsql-host').value,
        port: document.getElementById('tdsql-port').value,
        database: document.getElementById('tdsql-database').value,
        username: document.getElementById('tdsql-username').value,
        password: document.getElementById('tdsql-password').value
    };
    
    if (!config.secret_id || !config.secret_key || !config.region) {
        alert('请填写完整的腾讯云API配置信息');
        return;
    }
    
    const saveBtn = event.target;
    const originalText = saveBtn.textContent;
    saveBtn.textContent = '保存中...';
    saveBtn.disabled = true;
    
    // 使用通用API接口
    fetch('api/save_database_config.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: new URLSearchParams(config)
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('HTTP 错误: ' + response.status);
        }
        return response.text();
    })
    .then(text => {
        try {
            const data = JSON.parse(text);
            if (data.success) {
                alert('配置保存成功！');
                
                // 如果返回了数据库状态信息，显示互斥结果
                if (data.database_states) {
                    const enabledDb = Object.keys(data.database_states).find(db => data.database_states[db]);
                    if (enabledDb === 'tdsql_c') {
                        console.log('TDSQL-C已启用，其他数据库已禁用');
                    }
                }
            } else {
                alert('配置保存失败：' + data.message);
            }
        } catch (e) {
            console.error('返回内容:', text);
            alert('返回数据解析错误: ' + e.message);
        }
    })
    .catch(error => {
        alert('保存失败：' + error.message);
    })
    .finally(() => {
        saveBtn.textContent = originalText;
        saveBtn.disabled = false;
    });
};